package com.simon.hse.activity.contractor;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.simon.hse.R;
import com.simon.hse.activity.BaseActivity;
import com.simon.hse.adapter.CommonEmptyAdapter;
import com.simon.hse.adapter.CommonViewHolder;
import com.simon.hse.http.CommonCallBack;
import com.simon.hse.http.HttpManager;
import com.simon.hse.http.entity.ContractorCompanyOutput;
import com.simon.hse.http.entity.ContractorPersonInput;
import com.simon.hse.utils.ToastUtils;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;

/**
 * 供应商公司
 */
@SuppressWarnings("all")
@ContentView(R.layout.activity_constractor_company)
public class ConstractorCompanyActivity extends BaseActivity {
    @ViewInject(R.id.tv_common_title)
    TextView mTv_common_title;

    @ViewInject(R.id.iv_common_right)
    ImageView mIv_common_right;

    @ViewInject(R.id.et_constractor_company_search)
    EditText mEt_constractor_company_search;

    @ViewInject(R.id.smartrefresh)
    SmartRefreshLayout mSmartRefresh;

    @ViewInject(R.id.recyclerview)
    RecyclerView mRecyclerView;

    private int currentPage = 1, totalPage = 1;
    private CommonEmptyAdapter mCommonEmptyAdapter;
    private String companyName, companyId, constractor;
    private List<ContractorCompanyOutput.DataBean.PageDataBean> mListContractorCompany = new ArrayList<>();// 承包商列表
    private ContractorCompanyOutput.DataBean.PageDataBean pageDataBean;// 承包商
    private int choosePos = -1;// 当前选择的承包商下标

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String title = bundle.getString("TITLE");
            mTv_common_title.setText(title);
            companyName = bundle.getString("NAME");
            companyId = bundle.getString("ID");
        } else {
            mTv_common_title.setText("供应商选取");
        }

        initRecyclerView();
        initData();
    }

    @Event(value = {R.id.iv_common_left, R.id.iv_common_right})
    private void clickButton(View view) {
        switch (view.getId()) {
            case R.id.iv_common_left:
                Intent intent = new Intent();
                if (pageDataBean != null) {
                    Bundle bundle = new Bundle();
                    bundle.putString("NAME", pageDataBean.getContractorName());
                    bundle.putString("ID", pageDataBean.getId());
                    intent.putExtras(bundle);
                }
                setResult(RESULT_OK, intent);
                finish();
                break;
            case R.id.iv_common_right:
                startActivity(new Intent(ConstractorCompanyActivity.this, AddTrainRecordActivity.class));
                break;
        }
    }

    private void initRecyclerView() {
        mEt_constractor_company_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                constractor = charSequence.toString();
                mListContractorCompany.clear();
                initData();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mSmartRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (currentPage * 10 < totalPage) {
                    currentPage++;
                    initData();
                } else {
                    mSmartRefresh.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                mListContractorCompany.clear();
                initData();
            }
        });

        LinearLayoutManager llm = new LinearLayoutManager(ConstractorCompanyActivity.this);
        mRecyclerView.setLayoutManager(llm);
        // 如果Item够简单，高度是确定的，打开FixSize将提高性能
        mRecyclerView.setHasFixedSize(true);
        // 设置Item默认动画，加也行，不加也行
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setNestedScrollingEnabled(false);

        mCommonEmptyAdapter = new CommonEmptyAdapter(ConstractorCompanyActivity.this, R.layout.layout_item_constractor_company, mListContractorCompany);
        mCommonEmptyAdapter.setItemDatasListener(new CommonEmptyAdapter.ItemDatasListener<ContractorCompanyOutput.DataBean.PageDataBean>() {
            @Override
            public void setItemDatas(CommonViewHolder holder, ContractorCompanyOutput.DataBean.PageDataBean dataBean, final int position) {
                TextView tv_constractor_company = holder.getView(R.id.tv_constractor_company);
                CheckBox cb_constractor_company = holder.getView(R.id.cb_constractor_company);

                tv_constractor_company.setText(dataBean.getContractorName());
                if (choosePos == position) {
                    cb_constractor_company.setChecked(true);
                } else {
                    cb_constractor_company.setChecked(false);
                }

                cb_constractor_company.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        choosePos = position;
                        pageDataBean = mListContractorCompany.get(position);
                        mCommonEmptyAdapter.notifyDataSetChanged();
                    }
                });
            }
        });

        mCommonEmptyAdapter.setOnItemEmptyClickListener(new CommonEmptyAdapter.OnItemEmptyClickListener() {
            @Override
            public void setOnEmptyClickListener() {
                initData();
            }

            @Override
            public void setOnItemClickListener(View view, int position) {
                choosePos = position;
                pageDataBean = mListContractorCompany.get(position);
                mCommonEmptyAdapter.notifyDataSetChanged();
            }

            @Override
            public void setOnItemLongClickListener(View view, int position) {

            }
        });

        mCommonEmptyAdapter.setHasStableIds(true);
        mRecyclerView.setAdapter(mCommonEmptyAdapter);
    }

    /**
     * 获取供应商
     */
    private void initData() {
        ContractorPersonInput contractorPersonInput = new ContractorPersonInput();
        ContractorPersonInput.ModelBean modelBean = new ContractorPersonInput.ModelBean();
        if (!TextUtils.isEmpty(constractor)) {
            modelBean.setContractorName(constractor);
        }
        contractorPersonInput.setModel(modelBean);
        contractorPersonInput.setLimit(20);
        contractorPersonInput.setOffset(0);

        Call<String> call = HttpManager.getInstance().requestService().CONTRACTOR(HttpManager.getInstance().requestBody(contractorPersonInput));
        HttpManager.getInstance().requestCallBack(call, new CommonCallBack<String>() {
            @Override
            public void requestSuccess(String result) {
                ContractorCompanyOutput contractorPersonOutput = new Gson().fromJson(result, ContractorCompanyOutput.class);
                if (contractorPersonOutput.getResult().equals("Success")) {
                    totalPage = contractorPersonOutput.getData().getRowCount();
                    List<ContractorCompanyOutput.DataBean.PageDataBean> pageDataBeanList = contractorPersonOutput.getData().getPageData();
                    mListContractorCompany.addAll(pageDataBeanList);
                    for (int i = 0; i < mListContractorCompany.size(); i++) {
                        if (mListContractorCompany.get(i).getContractorName().equals(companyName)) {
                            choosePos = i;
                            pageDataBean = mListContractorCompany.get(i);
                        }
                    }
                    mCommonEmptyAdapter.notifyDataSetChanged();

                    mSmartRefresh.finishRefresh();
                    mSmartRefresh.finishLoadMore();
                } else {
                    ToastUtils.getInstance().showShortToastBottom(contractorPersonOutput.getMessage());
                }
            }

            @Override
            public void requestError(String errorMsg) {
                ToastUtils.getInstance().showShortToastBottom(errorMsg);
            }
        });
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        if (pageDataBean != null) {
            Bundle bundle = new Bundle();
            bundle.putString("NAME", pageDataBean.getContractorName());
            bundle.putString("ID", pageDataBean.getId());
            intent.putExtras(bundle);
        }
        setResult(RESULT_OK, intent);
        super.onBackPressed();
    }
}
